import logging
from datetime import datetime
from common.merchant.models import Merchant
from common.utils.db import list_object, get_object
from common.utils.maestro_exceptions import (
    MaestroException,
    ILLEGAL_PARAMETER
)

_LOGGER = logging.getLogger(__name__)


def get_merchant(query_dct):
    return get_object(query_dct, Merchant)


def list_merchant(query_dct):
    return list_object(query_dct, Merchant)


def create_merchant(merchant, desc):
    merchant = Merchant(
        merchant_name=merchant,
        desc=desc,
        created_at=datetime.utcnow(),
        updated_at=datetime.utcnow()
    )
    merchant.save()
    return merchant


def update_merchant(merchant_id, merchant_name, desc):
    merchant = Merchant.objects.filter(id=merchant_id).first()
    if not merchant:
        raise MaestroException(ILLEGAL_PARAMETER, '商户不存在')
    if merchant.merchant_name != merchant_name and Merchant.objects.filter(merchant_name=merchant_name).count() > 0:
        raise MaestroException(ILLEGAL_PARAMETER, '商户名重复')
    merchant.merchant_name = merchant_name
    merchant.desc = desc
    merchant.save()
    return {}
